//
//  OSCThread.m
//  oschina_song
//
//  Created by song on 16/2/18.
//  Copyright © 2016年 song. All rights reserved.
//

#import "OSCThread.h"
#import "Reachability.h"
#import "AFHTTPRequestOperationManager+Util.h"
#import "OSCAPI.h"
#import "Config.h"
#import "OSCNotice.h"

static BOOL isPollingStarted;
static NSTimer *timer;
static Reachability *reachability;

@interface OSCThread()
@end


@implementation OSCThread



+(void)startPollingNotice
{

    timer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
    reachability = [Reachability reachabilityWithHostName:@"www.oschina.net"];
    
    
}

/**
 <notice>
	<atmeCount>0</atmeCount>
	<msgCount>0</msgCount>
	<reviewCount>0</reviewCount>
	<newFansCount>0</newFansCount>
	<newLikeCount>0</newLikeCount>
 </notice>
 **/

+(void)timerUpdate
{
    if (reachability.currentReachabilityStatus ==0) {
        NSLog(@"网络断开了");
    }else{
        NSLog(@"很畅通！");
    }
    
    AFHTTPRequestOperationManager *manger =[AFHTTPRequestOperationManager OSCManger];
    NSString *url =[NSString stringWithFormat:@"%@%@",OSCAPI_PREFIX,OSCAPI_USER_NOTICE];
    [manger GET:url parameters:@{@"uid":@([Config getOwnID])} success:^(AFHTTPRequestOperation * _Nonnull operation, ONOXMLDocument *responseObject) {
        ONOXMLElement *notice  = [responseObject.rootElement firstChildWithTag:@"notice"];
        int atCount = [[[notice firstChildWithTag:@"atmeCount"] numberValue] intValue];
        int msgCount = [[[notice firstChildWithTag:@"msgCount"] numberValue] intValue];
        int reviewCount = [[[notice firstChildWithTag:@"reviewCount"] numberValue] intValue];
        int newFansCount = [[[notice firstChildWithTag:@"newFansCount"] numberValue] intValue];
        int newLikeCount = [[[notice firstChildWithTag:@"newLikeCount"] numberValue] intValue];
        
        OSCNotice *noticeobj =[[OSCNotice alloc] initWithAtCount:atCount msgCount:msgCount reviewCount:reviewCount newFansCount:newFansCount newLikeCount:newLikeCount];
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        path = [path stringByAppendingString:@"/notice.obj"];
        NSLog(@"path : %@",path);
        [NSKeyedArchiver archiveRootObject:noticeobj toFile:path];
        
        OSCNotice *tt =[NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"%@",tt);
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
    
}

@end
